package com.zl.tby.service.impl;

import com.zl.tby.core.base.util.ToolsUtil;
import com.zl.tby.core.common.R;
import com.zl.tby.dto.TbyUavInfoQuery;
import com.zl.tby.kafka.AnalysisUavData;
import com.zl.tby.kafka.UavList;
import com.zl.tby.kafka.UavListItem;
import com.zl.tby.kafka.UavNotify;
import com.zl.tby.model.TbyUavInfo;
import com.zl.tby.model.TbyUavKafka;
import com.zl.tby.repository.TbyUavKafkaRepo;
import com.zl.tby.service.ITbyUavInfoService;
import com.zl.tby.service.ITbyUavKafkaService;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Tran;
import org.noear.wood.DataItem;
import org.noear.wood.DbContext;
import org.noear.wood.DbTableQuery;
import org.noear.wood.annotation.Db;
import org.noear.wood.utils.StringUtils;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 接收无人机kafka的数据 接口实现
 * @author changpeng
 * @version 1.0
 * @since 2024/8/6 20:22
 */
@Slf4j
@Component
public class TbyUavKafkaServiceImpl implements ITbyUavKafkaService {

    @Db
    private TbyUavKafkaRepo tbyUavKafkaRepo;
    @Inject
    private ITbyUavInfoService uavInfoService;
    @Db
    private DbContext db;

    @Override
    @Tran
    public R<UavNotify> add(String content) {
        TbyUavKafka entity = new TbyUavKafka();
        entity.setContent(content);
        UavNotify notify = null;
        try {
            notify = AnalysisUavData.analysis(content);
            if (notify != null) {
                entity.setUavCode(notify.getDeviceID());
                if (StringUtils.isNotEmpty(notify.getTime())) {
                    String time = ToolsUtil.replaceStr(notify.getTime(), "T", " ");
                    entity.setReceiveTime(ToolsUtil.dateString2Util(time, "yyyy-MM-dd HH:mm:ss"));
                    if (notify.getUav() != null && notify.getUav().size() > 0) {
                        UavList uavList = notify.getUav().get(0);
                        if (uavList.getItem() != null && uavList.getItem().size() > 0) {
                            UavListItem item = uavList.getItem().get(0);
                            entity.setLongitude(item.getPosLongitude());
                            entity.setLatitude(item.getPosLatitude());
                        }
                    }
                }
            }
            entity.setStatus(1);
        } catch (Exception ex) {
            log.error("解析无人机kafka数据异常", ex);
            entity.setStatus(0);
        }
        entity.setCreateBy(-1L);
        entity.setCreateTime(LocalDateTime.now());
        long id = tbyUavKafkaRepo.insert(entity, true);
        entity.setId(id);
        if (entity.getStatus().compareTo(1) == 0) {
            this.uavInfoService.updateLonlat(entity.getUavCode(), entity.getLongitude(), entity.getLatitude());
        } else {
            this.uavInfoService.updateOnLine(entity.getUavCode());
        }
        return R.ok(notify);
    }

    @Override
    public void checkUavStatus() {
        try {
            List<TbyUavKafka> dataList = db.table("tby_uav_kafka").groupBy("uav_code").selectList("max(receive_time) as receive_time, uav_code", TbyUavKafka.class);
            if (dataList == null || dataList.size() == 0) {
                // 没有数据说明，铁定都是离线的
                DataItem data = new DataItem();
                data.set("status", 0);
                db.table("tby_uav_info").whereTrue().update(data);
                return;
            }
            Map<String, Long> uavMap = new HashMap<>(0);
            if (dataList != null && dataList.size() > 0) {
                for (TbyUavKafka tbyUavKafka : dataList) {
                    if (StringUtils.isNotEmpty(tbyUavKafka.getUavCode()) && tbyUavKafka.getReceiveTime() != null) {
                        uavMap.put(tbyUavKafka.getUavCode(), tbyUavKafka.getReceiveTime().getTime());
                    }
                }
            }
            // 获取全部无人机
            List<TbyUavInfo> uavList = this.uavInfoService.list(new TbyUavInfoQuery());
            for (TbyUavInfo uav : uavList) {
                if (!uavMap.containsKey(uav.getCode())) {
                    // 不存在，说明铁定是离线
                    this.uavInfoService.updateOffLine(uav.getId());
                    continue;
                }
                // 如果存在飞行的数据，验证时间大于1分钟认为是离线
                if ((System.currentTimeMillis() - uavMap.get(uav.getCode()).longValue()) > (1000 * 60)) {
                    this.uavInfoService.updateOffLine(uav.getId());
                }
            }
        } catch (Exception ex) {
            log.error("同步无人机状态异常", ex);
        }
    }

    @Override
    public List<TbyUavKafka> list() {
        // 查询设备ID相关的记录
        List<TbyUavKafka> dbList = this.tbyUavKafkaRepo.selectList(mp -> {

        });

        // 如果查询到的结果为空，返回一个空列表；否则返回查询结果
        return dbList.isEmpty() ? Collections.emptyList() : dbList;
    }
}
